import 'dart:convert';

import 'package:extended_image/extended_image.dart';
import 'package:gd_assistant/model/healthRecordModel.dart';
import 'package:gd_assistant/model/orderItemModel.dart';
import 'package:gd_assistant/model/patientModel.dart';
import 'package:gd_assistant/util/dataUtil.dart';
import 'package:gd_assistant/util/dioManager.dart';
import 'package:gd_assistant/model/extensionModel.dart';
import 'package:gd_assistant/model/userModel.dart';
import 'package:gd_assistant/model/packageModel.dart';

class apiHandler {
  
  //获取验证码
  static getAuthcode(String phoneNum) async {
    Map<String, dynamic> params = {
      "phoneNum": phoneNum,
      "from": ""
    };
     var result = await DioManager.getInstance().get('/1/common/authCode', params);
     return result;
  }

  //修改密码接口
  static changePassWord(String new_pwd, String code) async {
    var params = {
        "new_pwd": new_pwd,
        "code": code,
      };
    var result = await DioManager.getInstance().post('/1/assistant/user/update_pwd',params);
    return result;
  }

  //登录接口
  static assistantLogin(String phone_num, String pwd) async {
    var params = {
        "phone_num": phone_num,
        "pwd": keyToMd5(pwd).toUpperCase(),
        "type": 1
      };

    var result = await DioManager.getInstance().post('/1/assistant/userlogin',params);
    if (result != null) {
       Map data = result["data"];
       Assistant assistant = Assistant.fromJson(data);
       dataUtil.setValue(dataUtil.nickNameKey, assistant.nickName);
       dataUtil.setValue(dataUtil.assistantAvatarKey, assistant.avatar);
       dataUtil.setValue(dataUtil.assistantPhoneKey, assistant.phoneNum);
       dataUtil.setValue(dataUtil.tokenKey, assistant.token);
       dataUtil.setValue(dataUtil.assistantIdKey, assistant.sId);
      return assistant;
     }else {
       return null;
     }
  }

  //修改用户信息
  static updateAssistantInfo({String nick_name, String avatar}) async {
     Map<String, dynamic> params = {};
     if (nick_name != null) {
       params["nick_name"] = nick_name;
     }
     if (avatar != null) {
       params["avatar"] = avatar;
     }
     var result = await DioManager.getInstance().get('/1/assistant/user/update_info', params);
     return result;
   }

   //获取助理的评分
  static getEvaluationCount() async {
     Map<String, dynamic> params = {};
     var result = await DioManager.getInstance().get('/1/assistant/evaluation_count', params);
     if (result != null) {
       dataUtil.setValue(dataUtil.evaluationCountKey, result["data"]["count"].toString());
       dataUtil.setValue(dataUtil.markKey, result["data"]["mark"].toString());
     }
     return result;
   }

  //获取用户信息接口
  static getAssistantInfo() async {
     Map<String, dynamic> params = {};
     var result = await DioManager.getInstance().get('/1/assistant/user/info', params);
     if (result != null) {
       Map data = result["data"];
       Assistant assistant = Assistant.fromJson(data);
       dataUtil.setValue(dataUtil.nickNameKey, assistant.nickName);
       dataUtil.setValue(dataUtil.assistantAvatarKey, assistant.avatar);
       dataUtil.setValue(dataUtil.assistantPhoneKey, assistant.phoneNum);
      return assistant;
     }else {
       return null;
     }
   }

  //获取首页预约信息
  //全部：-100，未就诊:200，已就诊:400，已取消:300
  // String begin_at, String end_at, int status, List doctor_ids, int page_num
  static getMemberShipList(String begin_at,String status,List doctor_ids,int page_num) async {
    var b = int.parse(begin_at);
    var e = int.parse(begin_at) + 86400000;
    int s = 400;
    switch (status) {
      case "全部状态":
         s = -100;
        break;
      case "未就诊":
         s = 200;
        break;
      case "已就诊":
         s = 400;
        break;
      case "已取消":
         s = 300;
        break;    
      default:
    }
    var params = {
        "begin_at": b,
        "end_at": e,
        "status": s,
        "doctor_ids": doctor_ids,
        "page_num": page_num
      };

    var result = await DioManager.getInstance().post('/assistant/appointments',params);
    if (result != null) {
      List list = result["items"];
      return list.map((i)=>Extension.fromJson(i)).toList();
    }
    return List<Extension>();
   }

   //首页获取服务医生字母排序列表
   static getServicePackageDoctorMap() async {
     Map<String, dynamic> params = {};
     var result = await DioManager.getInstance().get('/service_package/doctor_map', params);
     if (result != null) {
       Map data = result["data"];
       return data;
     }else {
       return {};
     }
   }

   //获取预约详情
   static getAppointmentInfo(String orderId) async {
      var params = {
          "order_id": orderId
        };

      var result = await DioManager.getInstance().get('/assistant/appointment_info',params);
      if (result != null) {
        Map data = result["data"];
        return Extension.fromJson(data);
      }
      return Extension();
   }

   //page2 用户管理用户 查询/搜索/筛选用户
   static getAssistantSearchUserList(String search, String doctorid, int status, int page_num) async {
     Map<String, dynamic> params = {
       "status": status,
       "page_num": page_num,
       "page_size": 20
     };
     if (search.isNotEmpty) {
       params["keywords"] = search;
     }
     if (doctorid.isNotEmpty) {
       params["doctorid"] = doctorid;
     }
     var result = await DioManager.getInstance().get('/assistant/search_users_v1', params);
     if (result != null) {
       Map data = result["data"];
       return UserModel.fromJson(data);
     }else {
       return UserModel(items: []);
     }
   }

   //查询会员购买过的服务包
   static getMemberServicePackageList(String userid) async {
     Map<String, dynamic> params = {
       "user_id": userid
     };
     var result = await DioManager.getInstance().get('/assistant/member_service_package',params);
     if (result != null) {
       List list = result["items"];
       return list.map((i)=>PackageModel.fromJson(i)).toList();
     }else {
       return List<PackageModel>();
     }
   }

   //拉取就诊人列表
   static getPatientList(String customerId) async {
     var params = {
        "user_id": customerId
      };
      var result = await DioManager.getInstance().get('/1/service_package/patient_list',params);
      if (result != null) {
        List list = result["items"];
        return list.map((i)=>PatientModel.fromJson(i)).toList();
      }else {
        return List<PatientModel>();
      }
   }

   //拉取助理列表
   static getServPackageAssistant(String doctorId) async {
     var params = {
        "doctor_id": doctorId
      };
      var result = await DioManager.getInstance().get('/1/applet/service_package_assistant',params);
      if (result != null) {
       return UserModel.fromJson(result);
     }else {
       return UserModel(items: []);
     }
   }

   //新增就诊人信息
   static postNewPatientInfo(String assistantId, String commonUsedPatientId, String orderId, String isNewPatient) async {
      var params = {
        "assistant_id": assistantId,
        "common_used_patient_id": commonUsedPatientId,
        "orderId": orderId,
        "is_new_patient": isNewPatient
      };

      var result = await DioManager.getInstance().post('/1/service_package/create_patient_info',params);
      return result;
   }

   //获取助理端用户相关预约订单列表
   static getAppointmentOrderList(String userid, String orderid) async {
     Map<String, dynamic> params = {
       "user_id": userid,
       "servicePackageOrderId": orderid
     };
     var result = await DioManager.getInstance().get('/assistant/servicePackage/make_appointment_orders',params);
     if (result != null) {
       List list = result["items"];
       return list.map((i)=>Extension.fromJson(i)).toList();
     }else {
       return List<Extension>();
     }
   }

   //获取健康档案列表
   static getHealthRecordList(String userid, String orderid) async {
     Map<String, dynamic> params = {
       "user_id": userid,
       "service_package_order_id": orderid
     };
     var result = await DioManager.getInstance().get('/assistant/cases',params);
     if (result != null) {
       List list = result["items"];
       return list.map((i)=>HealthRecordModel.fromJson(i)).toList();
     }else {
       return List<HealthRecordModel>();
     }
   }

   //会员资料详情
   static getMemberDetail(String userid, String orderid) async {
     Map<String, dynamic> params = {
       "user_id": userid,
       "order_id": orderid
     };
     var result = await DioManager.getInstance().get('/assistant/member_detail',params);
     if (result != null) {
       Map data = result["data"];
       return PatientModel.fromJson(data);
     }else {
       return PatientModel();
     }
   }

   //获取检查项目
   static getOrderItems() async {
     Map<String, dynamic> params = {};
     var result = await DioManager.getInstance().get('/service_package/make_appointment_order/items',params);
     if (result != null) {
       List list = result["items"];
       return list.map((i)=>OrderItem.fromJson(i)).toList();
     }else {
       return List<OrderItem>();
     }
   }

   //获取医疗包的预约日期     
   static getPackageAppointmentList(String servicePackageOrderId) async {
     Map<String, dynamic> params = {
       "servicePackageOrderId": servicePackageOrderId
     };
     var result = await DioManager.getInstance().get('/1/servicePackage/make_appointment_list',params);
     if (result != null) {
       List list = result["items"];
       return list.map((i)=>AppointmentTime.fromJson(i)).toList();
     }else {
       return List<AppointmentTime>();
     }
   }

   //获取医疗包的 预约具体时间     
   static getPackageAppointmentTime(String servicePackageOrderId, int time, int visitPlanPeriod) async {
     Map<String, dynamic> params = {
       "servicePackageOrderId": servicePackageOrderId,
       "time": time,
       "visitPlanPeriod": visitPlanPeriod
     };
     var result = await DioManager.getInstance().get('/1/servicePackage/make_appointment_time',params);
     if (result != null) {
       return WorkTime.fromJson(result);
     }else {
       return WorkTime(bookedTimes: [],workTimes: []);
     }
   }

   //获取上传的token 地址等信息
   static getUploadToken() async{
     Map<String, dynamic> params = {};
     var result = await DioManager.getInstance().get('/1/common/cdn',params);
     if (result != null) {
       dataUtil.setValue(dataUtil.upLoadTokenKey, result["token"]);
     }
     //还没处理
   }

   //修改健康档案信息
   static updateCase(String caseId, int checkTime, List<String> selectedReservations, String checkDetail, String meProblem, String doctorSolution, String otherPoints, List<String> checkImgs) async {
    var params = {
        "case_id": caseId,
        "check_time": checkTime,
        "selected_reservations": selectedReservations,
        "check_detail": checkDetail,
        "meProblem": meProblem,
        "doctorSolution": doctorSolution,
        "otherPoints": otherPoints,
        "check_imgs": checkImgs
      };

    var result = await DioManager.getInstance().post('/1/assistant/cases_update',params);
    return result;
   }

   //新增就诊人信息
   static createCommonPatient(String name, int birth, String sex, String medical_number, int last_menstruation, String phone_num, int expected_date, String userId, int baby_birth, String note, String allergy_history, String cost_type, String area, String address) async {
      var params = new Map<String,dynamic>();
     params = {
        "user_id": userId,
        "phone_num": phone_num,
        "name": name,
        "sex": sex,
        "medical_number": medical_number,
        "allergy_history": allergy_history,
        "note": note,
        "cost_type": cost_type,
        "area": area,
        "address": address
      };
      if (birth != 0) {
        params["birth"] = birth;
      }
      if (last_menstruation != 0) {
        params["last_menstruation"] = last_menstruation;
      }
      if (expected_date != 0) {
        params["expected_date"] = expected_date;
      }
      if (baby_birth != 0) {
        params["baby_birth"] = baby_birth;
      }
  
    var result = await DioManager.getInstance().post('/1/service_package/create_common_patient',params);
    if (result != null) {
       Map data = result["data"];
       return PatientModel.fromJson(data);
     }else {
       return result;
     }
   }

   //新增健康档案信息
   static createNewCase(String user_id, String service_package_order_id, int checkTime, List<String> selectedReservations, String checkDetail, String meProblem, String doctorSolution, String otherPoints, List<String> checkImgs) async {
     var params = {
        "check_time": checkTime,
        "selected_reservations": selectedReservations,
        "check_detail": checkDetail,
        "meProblem": meProblem,
        "doctorSolution": doctorSolution,
        "otherPoints": otherPoints,
        "check_imgs": checkImgs,
        "service_package_order_id": service_package_order_id,
        "user_id": user_id
      };

    var result = await DioManager.getInstance().post('/1/assistant/add_case',params);
    return result;
   }

   //修改预约
   static updateAppointment(String orderId, int workTime, List<String> items, String address, String instructions, String status, List<String> checklist_imgs) async {
     var params = {
        "workTime": workTime,
        "items": items,
        "address": address,
        "instructions": instructions,
        "status": status,
        "checklist_imgs": checklist_imgs,
        "orderId": orderId
      };

    var result = await DioManager.getInstance().post('/1/service_package/make_appointment_order/update',params);
    return result;
   }

   //新建预约
   static createAppointment(String user_id, String servicePackageOrderId, int workTime, List<String> items, String address, String instructions, List<String> checklist_imgs) async {
     var params = {
        "user_id": user_id,
        "workTime": workTime.toString(),
        "items": items,
        "address": address,
        "instructions": instructions,
        "checklist_imgs": checklist_imgs,
        "servicePackageOrderId": servicePackageOrderId,
        "screct": DateTime.now().millisecondsSinceEpoch
      };

    var result = await DioManager.getInstance().post('/1/assistant/servicePackage/make_appointment_orders/create',params);
    return result;
   }

   //修改就诊人信息
   static updatePatientInfo(String patient_info_id, String name, String phone_num, int birth, String sex, String medical_number, int last_menstruation, int expected_date, int baby_birth, String allergy_history, String note, String cost_type, String area, String address) async {
     
     var params = new Map<String,dynamic>();
     params = {
        "patient_info_id": patient_info_id,
        "phone_num": phone_num,
        "name": name,
        "sex": sex,
        "medical_number": medical_number,
        "allergy_history": allergy_history,
        "note": note,
        "cost_type": cost_type,
        "area": area,
        "address": address
      };
      if (birth != 0) {
        params["birth"] = birth;
      }
      if (last_menstruation != 0) {
        params["last_menstruation"] = last_menstruation;
      }
      if (expected_date != 0) {
        params["expected_date"] = expected_date;
      }
      if (baby_birth != 0) {
        params["baby_birth"] = baby_birth;
      }
  
    var result = await DioManager.getInstance().post('/1/assistant/member_update',params);
    return result;
   }
}